package org.lonetree.tc.dao.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public abstract class HibernateHelper{
	
	private static final String HIBERNATE_CFG_XML = "org/lonetree/tc/dao/hibernate/hibernate.cfg.xml";
	private static SessionFactory sessionFactory;
	private static Session session;

	public static Session getSession(){
		if(sessionFactory == null)
			sessionFactory = new Configuration().configure(HIBERNATE_CFG_XML).buildSessionFactory();
		
		if(session == null)
			session = sessionFactory.openSession();
		
		return session;
	}
	
	public static Object executeHibernateAction(HibernateAction action){
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		try{
			Object retObj = action.execute(session);
			session.flush();
			tx.commit();
			return retObj;
		}
		catch(RuntimeException e){
			tx.rollback();
			throw e;
		}
	}
}
